package com.shujia.sql

import org.apache.flink.table.api.{EnvironmentSettings, TableEnvironment}

object Demo1WordCount {
  def main(args: Array[String]): Unit = {
    /**
      * \、创建Flink sql环境
      *
      */

    val settings: EnvironmentSettings = EnvironmentSettings
      .newInstance()
      .inStreamingMode()//流处理模式
      //.inBatchMode()//批处理模式
      .build()

    val table: TableEnvironment = TableEnvironment.create(settings)

    /**
      * 1、创建一个source 表
      * 读取kafka中的数据
      *
      */

    table.executeSql(
      """
        |CREATE TABLE words (
        |  word STRING
        |) WITH (
        |  'connector' = 'kafka',
        |  'topic' = 'words',
        |  'properties.bootstrap.servers' = 'master:9092',
        |  'properties.group.id' = 'testGroup',
        |  'scan.startup.mode' = 'earliest-offset',
        |  'format' = 'csv',
        |  'csv.field-delimiter'='\t'
        |)
        |
      """.stripMargin)


    /**
      * 2、创建一个sink表
      * 将数据保存到mysql中
      *
      */
    table.executeSql(
      """
        |CREATE TABLE word_count (
        |  word STRING,
        |  c BIGINT,
        |  PRIMARY KEY (word) NOT ENFORCED
        |) WITH (
        |   'connector' = 'jdbc',
        |   'url' = 'jdbc:mysql://master:3306/bigdata',
        |   'table-name' = 'word_count',
        |   'username' = 'root',
        |   'password' = '123456'
        |)
      """.stripMargin)


    /**
      * 统计单词的数量
      */

    table.executeSql(
      """
        |insert into word_count
        |select word,count(1) as c from words
        |group by word
        |
      """.stripMargin)


  }

}
